from cryptography.fernet import Fernet
import base64
import hashlib


class CryptoUtils:
    @staticmethod
    def get_fernet_key(password: str):
        """从密码生成Fernet密钥"""
        hlib = hashlib.md5()
        hlib.update(password.encode('utf-8'))
        return base64.urlsafe_b64encode(hlib.hexdigest().encode('latin-1'))

    @staticmethod
    def encrypt(text: str, password: str) -> str:
        """加密文本"""
        f = Fernet(CryptoUtils.get_fernet_key(password))
        encrypted = f.encrypt(text.encode('utf-8'))
        return encrypted.decode('utf-8')

    @staticmethod
    def decrypt(encrypted_text: str, password: str) -> str:
        """解密文本"""
        f = Fernet(CryptoUtils.get_fernet_key(password))
        decrypted = f.decrypt(encrypted_text.encode('utf-8'))
        return decrypted.decode('utf-8')
